package com.apes.scm.masterdata.party.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.service.BusinessParamService;
import com.apes.scm.masterdata.finance.model.BankAccount;
import com.apes.scm.masterdata.finance.repository.BankAccountRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 功能：当事人角色
 *
 * @author bieb
 * @create 2018-8-9 10:44:20
 */
@Service("partyRoleService")
public class PartyRoleService extends DomainService {

    @Autowired
    PartyRoleRepository partyRoleRepository;

    @Autowired
    private CorporateSerive corporateSerive;

    /***
     * 通过 party_id role_id 查询当事人角色信息
     * @param request
     * @return
     */
//    public List<PartyRole> findByPartyIdAndRoleId(SimpleRequest request) {
//        JSONObject tempObj = request.getJO();
//        return partyRoleRepository.findByRole(tempObj.getLong("party_id"), tempObj.getString("role_id"));
//    }
    public Map findByPartyId(SimpleRequest request) {
        Long partyId;
        if (request.get("id") == null) {
            partyId = Long.parseLong(request.getJO().getJSONObject("party").getString("id"));
        } else {
            PartyRole partyRole = partyRoleRepository.findOne((String) request.get("id"));
            partyId = partyRole.getParty().getId();
        }
        return MapUtil.mapper(
                "customers", partyRoleRepository.findByPartyId(partyId)
        );

    }

    public Page<PartyRole> findAll(SimpleRequest request) {
        return partyRoleRepository.findAll(PageRequest.of(request.get("page"), request.get("size")));
    }

    public PartyRole findOne(String id, String roleId) {
        return partyRoleRepository.findByIdAndRoleId(id, roleId);
    }
    public PartyRole findByOrigin(String origin){
        return partyRoleRepository.findPartyRole(origin);

    }

    public PartyRole findByPartyAndRole(long id, String roleId) {
        PartyRole partyRole = partyRoleRepository.findByPartyIdAndRoleId(id, roleId);
        if( partyRole == null ) throw new RuntimeException("未找到当前Party对应" + roleId + "类型的数据，Party编码：" + id);
        return partyRole;
    }

    public Page<PartyRole> findByRole(SimpleRequest request, String roleId) {
        JSONObject tempObj = request.getJO();
        Sort sort = new Sort(Sort.Direction.ASC, "code");
        return partyRoleRepository.findByRole(tempObj.getString("code"), roleId, PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    /*
    *  配合 findAll 插件 添加角色, 当事人类型等
   */
    public String addPartyTypeAndRoleId(SimpleRequest simpleRequest, String partyType, String roleId) {
        Map map = simpleRequest.getMap();
        List<Map<String, Object>> condition = new ArrayList<Map<String, Object>>();
        if (map.containsKey("condition")) {
            condition = (List<Map<String, Object>>) map.get("condition");
        }
        if (map.containsKey("key")) {
            Map filter = new HashMap();
            String id = (String) map.get("key");
            try {
                Integer.parseInt(id);
                filter.put("field", "id");
            } catch (NumberFormatException e) {
                filter.put("field", "party.name");
            }
            filter.put("operator", "LIKE");
            filter.put("value", id);
            condition.add(filter);
        }
        // 角色类型
        Map roleParams = new HashMap<>();
        roleParams.put("field", "role.id");
        roleParams.put("operator", "EQ");
        roleParams.put("value", roleId);
        condition.add(roleParams);
        // 当事人类型
        Map typeParams = new HashMap<>();
        typeParams.put("field", "party.partyType");
        typeParams.put("operator", "EQ");
        typeParams.put("value", partyType);
        condition.add(typeParams);
        map.put("condition", condition);
        return map.toString();
    }


    /*
     * 按部门查询销售员
     */
    public Map findSalesmanByDeptId(SimpleRequest request) {
        JSONObject jo = request.getJO();
        List<PartyRole> roles = partyRoleRepository.findAllSalesmanByDeptId(jo.getString("deptId"));
        return MapUtil.mapper("total", roles.size(), "pages", 1, "page", 1, "size", roles.size(), "content", roles);
    }



    /*
     * 按部门查询销售员
     */
    public Map findByDutyCenter(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONObject group = jo.getJSONObject("group");
        JSONArray filters = group.getJSONArray("filters");
        JSONObject filter = filters.getJSONObject(0);
        String dutyCenterId = filter.getString("value");
        if (dutyCenterId==null||dutyCenterId.equals(""))throw new RuntimeException("请先选择责任中心。");
        List<Dept> deptList = SpringManager.getBean(DeptRepository.class).findByProfitCenterId(dutyCenterId);
        List<PartyRole> roles = new ArrayList<>();
        for (int i = 0; i < deptList.size(); i++) {
            roles.addAll(partyRoleRepository.findAllSalesmanByDeptId(deptList.get(i).getId()));
        }
        return MapUtil.mapper("total", roles.size(), "pages", 1, "page", 1, "size", roles.size(), "content", roles);
    }

    /**
     * 根据编码或者名称查询单位客户信息
     * @param request
     * @return
     */
    public Page<PartyRole> findCustomerByIdOrName(SimpleRequest request) {
        JSONObject requestObj = request.getJO();
        String key = requestObj.getString("key");
       return partyRoleRepository.findCustomerByIdOrName(key,key,PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 添加单位客户和供应商查询条件
     * @param request
     * @return
     */
    public String addPartyTypeAndMultipleRoles(SimpleRequest request) {
        return addPartyTypeAndMultipleRoles(request, "corporate", "Supplier","Customer","Operator","Company");
    }

    /**
     *  配合 findAll 插件 添加多个角色, 当事人类型等
     */
    public String addPartyTypeAndMultipleRoles(SimpleRequest simpleRequest, String partyType, String... roleIds) {
        Map map = simpleRequest.getMap();
        List<Map<String, Object>> condition = new ArrayList<Map<String, Object>>();
        if (map.containsKey("condition")) {
            condition = (List<Map<String, Object>>) map.get("condition");
        }
        if (map.containsKey("key")) {
            Map filter = new HashMap();
            String id = (String) map.get("key");
            try {
                Integer.parseInt(id);
                filter.put("field", "id");
            } catch (NumberFormatException e) {
                filter.put("field", "party.name");
            }
            filter.put("operator", "LIKE");
            filter.put("value", id);
            condition.add(filter);
        }
        // 角色类型
        condition.add(mapper("field", "role.id","operator", "in","value", Arrays.asList(roleIds)));
        // 当事人类型
        condition.add(mapper("field", "party.partyType","operator", "EQ","value", partyType));
        map.put("condition", condition);
        return map.toString();
    }

    /**
     * 获取有效的收款信息
     * @param request
     * @return
     */
    public Map findGatheringInfoById(SimpleRequest request) {
        String partRoleId = request.get("partRoleId");
        List<BankAccount> bankAccounts = SpringManager.getBean(BankAccountRepository.class).findAll(JpaDsl.toCriteriaByEq("company.id", partRoleId));
        BankAccount bankAccount = new BankAccount();
        if (bankAccounts.size() > 0 ) {
            bankAccount = bankAccounts.stream().findFirst().orElse(new BankAccount());
        }

        return mapper("accountBank", bankAccount.getAccountName(), "bank", !Objects.isNull(bankAccount.getBank())?bankAccount.getBank().getName():null, "subbranch", bankAccount.getBankBranch(), "bankAccount", bankAccount.getAccountId());
    }


    // 获取全部公司
    public List<Map> allCompany() {
        return partyRoleRepository.allCompany();
    }

    /*
     * 按有效性查询所有partyRole
     */
    @Autowired
    DeptRepository  deptRepository;
    public Map findAllByValid(SimpleRequest request) {
        List<PartyRole> partyRoles;
        if(request.getJO().get("key") == null) {
             partyRoles = partyRoleRepository.findAllByValid();
        } else {
            String key = request.get("key").toString();
            List<Dept> deptList = deptRepository.findLikeName(key);
            List<String> strings = new ArrayList<>();
            strings.add(key);
            deptList.stream().collect(Collectors.groupingBy(Dept::getCompany)).forEach((getCompany, expenseItems)->{
                strings.add(getCompany.getId());
            });
            partyRoles = partyRoleRepository.findAllByValidAndKey(key,strings);
        }
        List<Map> partyRolesMap = MapUtil.mapped(partyRoles);
        partyRolesMap.forEach(map ->
                map.put("companyValid",Objects.isNull(partyRoleRepository.findOne(map.get("id").toString()).getParty().getCorporate()) ? false : partyRoleRepository.findOne(map.get("id").toString()).getParty().getCorporate().isValid()));
        return MapUtil.mapper("total", partyRolesMap.size(), "pages", 1, "page", 1, "size",  partyRolesMap.size(), "content", partyRolesMap);
    }

    /**
     * 功能：上级公司
     **/
    public PartyRole getParentCompany(SimpleRequest request) {
        BusinessParam bp = getBean(BusinessParamService.class).getParentCompany(request);
        if (bp == null) return null;
        return partyRoleRepository.findOne(bp.getValue());
    }

    /**
     * 获取运营模式为赋能店partyRole数据
     * @param request
     * @return
     */
    public JSONObject queryOperationByFn(SimpleRequest request){
        JSONObject result = new JSONObject();
        JSONObject requestJO = request.getJO();
        String key = requestJO.getString("key");

        List<PartyRole> partyRoles = partyRoleRepository.queryOperationByFn(key,PageRequest.of(request.get("page"), request.get("size")));
        result.put("content",partyRoles);
        result.put("page",request.get("page"));
        result.put("size",request.get("size"));
        return result;
    }

    public Map findAllByContract(SimpleRequest request){
        JSONObject jo = request.getJO();
        //用户输入参数
        String key = jo.get("key").toString();
        List<PartyRole> partyRoles = new ArrayList<>();
        //查询审核状态赋能合同公司
        List<String> lists = partyRoleRepository.findAllByContract();
        //转为partyRole
        lists.forEach(list -> partyRoles.add(partyRoleRepository.findOne(list)));
        List<Map> partyRolesMap;
        if("".equals(key)){
            partyRolesMap = MapUtil.mapped(partyRoles);
        } else {
            List<PartyRole> collect = partyRoles.stream().filter(partyRole -> partyRole.getId().equals(key) || partyRole.getName().equals(key)).collect(Collectors.toList());
            partyRolesMap = MapUtil.mapped(collect);
        }
        return MapUtil.mapper("total", partyRolesMap.size(), "pages", 1, "page", 1, "size",  partyRolesMap.size(), "content", partyRolesMap);
    }
}

